package cn.chengpengper.transfer.action;

import cn.chengpengper.transfer.listener.TranslateListener;
import cn.chengpengper.transfer.provider.TranslatorTextProvider;
import cn.chengpengper.transfer.storage.TranslatorCache;
import cn.chengpengper.transfer.util.TranslatorUtils;
import cn.chengpengper.transfer.window.TranslatorToolsWindow;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.util.messages.MessageBus;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

public class TranslatorAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        if (TranslatorUtils.appId == null || TranslatorUtils.securityKey == null) {
            Notifications.Bus.notify(new Notification("Translator", "小天才翻译机", "请先设置appId与securityKey", NotificationType.ERROR));
        }
        Project project = e.getRequiredData(CommonDataKeys.PROJECT);
        MessageBus messageBus = project.getMessageBus();
        TranslateListener publisher = messageBus.syncPublisher(TranslateListener.TRANSLATE_TOPIC);
        publisher.beforeTranslated(project);

        Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
        // 获取选中的文本
        String text = editor.getSelectionModel().getSelectedText();
        String result;
        Map<String, String> transCache = TranslatorCache.getInstance(e.getRequiredData(CommonDataKeys.PROJECT)).transCache;
        if (transCache.containsKey(text)) {
            result = transCache.get(text);
        } else {
            result = TranslatorUtils.getTransResult(text, "auto", "zh");
            if (!"翻译出错".equals(result)) {
                transCache.put(text, result);
                TranslatorToolsWindow.addNote(text, result);
            }
        }
        // 点击翻译按钮时，将原文与译文添加到自动提示 provider 的提示列表中
        TranslatorTextProvider.items.add(text);
        TranslatorTextProvider.items.add(result);
        Notifications.Bus.notify(new Notification("Translator", "小天才翻译机", result, NotificationType.INFORMATION));
        publisher.afterTranslated(project);
    }
}
